import Maycard from "@/components/may-card";
import logoImg from "@/assets/logo.png";
import mascot from "@/assets/mascot.png";
import chatold from "@/assets/icon/chatold.png";
import { ArrowRightOutlined } from "@ant-design/icons";
import { Select } from "antd";
import { useState, useEffect, useRef } from "react";

// 数据配置
const chatlist = [
  { value: "文心一言", label: "文心一言" },
  { value: "豆包", label: "豆包" },
  { value: "ChatGPT", label: "ChatGPT" },
  { value: "DeepSssk", label: "DeepSssk" },
];

const chatoldlist = [
  { value: "1987301973", label: "优化流程的方法" },
  { value: "9837429298", label: "写一个文档" },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
  {
    value: "8642102713",
    label: "1如何排除线上故障，给出具体方法和代码，写出完整demo",
  },
];

// 左侧卡片
const Leftcard = ({
  onChatChange,
}: {
  onChatChange: (value: string) => void;
}) => (
  <div className="mr-5 w-87 flex flex-col items-center">
    <div className="flex w-full justify-between">
      <img className="w-51 h-[208px] cursor-pointer" src={mascot} alt="" />
      <div className="w-33 h-[190px] cursor-pointer bg-[#E3F1FF] rounded-[2px_20px_20px_20px]"></div>
    </div>
    <Select
      style={{ width: "90%", marginTop: "20px" }}
      options={chatlist}
      onChange={onChatChange}
    />
    <div className="w-full flex-1 max-h-full pl-[10%] mt-5 flex flex-col overflow-hidden">
      <div className="maycard-header flex items-center text-[18px] font-bold mb-4">
        <div className="w-1.5 h-5 bg-[#236BFF]" />
        <span className="ml-4">历史对话</span>
      </div>
      <div className="flex-1 max-h-full overflow-y-auto scroll-smooth scrollbar-custom">
        {chatoldlist.map((item, index) => (
          <div key={index}>
            <div className="flex items-center mb-4 cursor-pointer hover:bg-[#edf5fa] hover:rounded-4 p-1">
              <img src={chatold} alt="" className="w-5 h-auto mr-3 ml-5" />
              <span className="text-[16px] whitespace-nowrap overflow-hidden text-ellipsis">
                {item.label}
              </span>
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// 聊天记录组件
const Chathistory = ({
  messages,
  historyRef,
}: {
  messages: { text: string; from: "user" | "bot" }[];
  historyRef: React.RefObject<HTMLDivElement>;
}) => (
  <div
    className="w-full flex-1 max-h-full mb-5 space-y-4 overflow-y-auto scroll-smooth scrollbar-custom"
    ref={historyRef}
  >
    {messages.map((msg, idx) => (
      <div
        key={idx}
        className={`flex ${msg.from === "user" ? "justify-end" : ""}`}
      >
        <div
          className={`px-4 py-2 rounded-[10px] max-w-[90%] ${
            msg.from === "user" ? "bg-[#cadbff]" : ""
          } text-black`}
        >
          {msg.text}
        </div>
      </div>
    ))}
  </div>
);

// 聊天框
const Chatbox = ({ chatLabel }: { chatLabel: string }) => {
  const [inputValue, setInputValue] = useState("");
  const [messages, setMessages] = useState<
    { text: string; from: "user" | "bot" }[]
  >([]);
  const [botTyping, setBotTyping] = useState(false);

  const historyRef = useRef<HTMLDivElement>(null);

  const handleSend = () => {
    if (!inputValue.trim()) return;
    const userMessage = { text: inputValue, from: "user" as const };
    setMessages((prev) => [...prev, userMessage]);
    setInputValue("");
    simulateBotTyping(
      "这是模拟的回答内容，逐字展示。《蜡笔小新》（日语：クレヨンしんちゃん，英语：Crayon Shin-chan）是臼井仪人创作的漫画作品。漫画以日本埼玉县春日部市一名5岁男童野原新之助的日常生活展开。此漫画于1990年在周末《漫画Action》开始连载，2000年移至月刊《Manga Town》连载。2009年9月11日，臼井仪人因登山意外身亡，本漫画成为未完成之遗作；其后于2010年由长期协助臼井仪人的助手组成的“臼井仪人＆UY Studio”续载，并取名为《新蜡笔小新》（新クレヨンしんちゃん）[1]。1992年开始由SHIN-EI动画制作电视动画，在朝日电视台播出。并于1993年开始由东宝制作，每年播出一部电影版。在其动画和漫画上臼井仪人旁均提有“らくだ社（骆驼社）”字样，据知是臼井自行设立的公司[2]。至今，动画版已有超过30种语言配音，并已连续放送32年（2024年）。"
    );
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      e.preventDefault();
      handleSend();
    }
  };

  // 打字效果函数
  const simulateBotTyping = (fullText: string) => {
    setBotTyping(true);
    let index = 0;
    const interval = setInterval(() => {
      index++;
      const currentText = fullText.slice(0, index);
      setMessages((prev) => {
        const last = prev[prev.length - 1];
        if (last?.from === "bot") {
          return [
            ...prev.slice(0, -1),
            { text: currentText, from: "bot" as const },
          ];
        } else {
          return [...prev, { text: currentText, from: "bot" as const }];
        }
      });
      if (index >= fullText.length) {
        clearInterval(interval);
        setBotTyping(false);
      }
    }, 50);
  };

  useEffect(() => {
    if (historyRef.current) {
      historyRef.current.scrollTop = historyRef.current.scrollHeight;
    }
  }, [messages]);

  return (
    <div className="flex-1 w-full h-full flex flex-col text-4">
      <div className="flex items-center h-10">
        <img className="w-32 h-10" src={logoImg} alt="" />
        <div className="w-[2px] h-full bg-[#236BFF] mx-[20px]"></div>
        <span className="text-9 leading-none font-bold">智能问答系统</span>
      </div>
      <div className="bg-[#EDF5FA] pt-5 pb-5 pl-20 pr-20 rounded-[20px] flex-[1] mt-5 flex flex-col overflow-hidden">
        <div className="maycard-header flex items-center text-[18px] font-bold mb-4">
          <div className="w-1.5 h-5 bg-[#236BFF]" />
          <span className="ml-4">{chatLabel}</span>
        </div>
        <Chathistory messages={messages} historyRef={historyRef} />
        <div className="pl-2.5 pr-1 ml-[auto] mr-[auto] w-full rounded-24 h-13 mt-auto border-[#236BFF] border-[1px] flex items-center">
          <input
            className="w-full h-full outline-none border-none"
            type="text"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyDown={handleKeyDown}
          />
          <div
            className="h-11 w-11 rounded-[50%] bg-[#c9d7f4] flex items-center justify-center cursor-pointer"
            onClick={handleSend}
          >
            <ArrowRightOutlined style={{ color: "#236bfe" }} />
          </div>
        </div>
      </div>
    </div>
  );
};

// 页面容器
const Dialogcard = () => {
  const [chatLabel, setChatLabel] = useState("交互机器人"); // 默认标题

  const handleChatChange = (value: string) => {
    setChatLabel(value); // 设置为当前选项的 label
  };

  return (
    <Maycard className="!pt-[30px] !pr-[50px] !pb-[40px] !pl-[20px]">
      <div className="flex w-full h-full">
        <Leftcard onChatChange={handleChatChange} />
        <Chatbox chatLabel={chatLabel} />
      </div>
    </Maycard>
  );
};

export default Dialogcard;
